﻿using _111.Models;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace Xsh.QyapiWeixinPlatform.Base.Util
{
    /// <summary>
    /// 网络工具类
    /// 加密模式：AES/CBC/PKCS5Padding
    /// 密钥长度：128位
    /// </summary>
    public class NetUpdateHelper
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public NetUpdateHelper(IHttpClientFactory httpClientFactory, IConfiguration configuration)
        {
            _httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// 数据流转String
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public async Task<string> StreamToStringAsync(Stream stream)
        {
            if (stream.CanSeek)
            {
                stream.Seek(0, SeekOrigin.Begin);
            }

            using (StreamReader reader = new StreamReader(stream))
            {
                return await reader.ReadToEndAsync();
            }
        }

        /// <summary>
        /// 获取企业微信token标准方法
        /// </summary>
        /// <param name="corpId"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public async Task<string> GetAccessTokenAsync(string corpId,string secret)
        {
            
            var Secret = AesCbcHelper.Encrypt(secret, System.Text.Encoding.Default.GetBytes("xshAesKey1234567"), System.Text.Encoding.Default.GetBytes("1234567890abcdef"));

            var content = new
            {
                mode = "qywxupdate",
                corpId = corpId,
                secret = Secret
            };

            var client = _httpClientFactory.CreateClient();
            client.DefaultRequestHeaders.Add("ContentType", "application/json");

            var postContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");

            var response = await client.PostAsync("http://ziyan.xshhotels.cn:8687/qwApi/getToken", postContent);


            if (response.IsSuccessStatusCode)
            {
                var responseStream = await response.Content.ReadAsStreamAsync();

                using (responseStream)
                {
                    var res = await StreamToStringAsync(responseStream);
                    var result = JsonConvert.DeserializeObject<TokenResponse>(res);
                    if (result != null && result.code == 200)
                    {
                        return result.body;
                    }
                }

            }
            return "";
        }

        /// <summary>
        /// 企业微信推送自定义功能标准方法
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<string> UpdateUserWorkbenchDataAsync(QywxUpdateDetail request)
        {
            var token = await GetAccessTokenAsync(request.CorpId,request.Secret);
            var client = _httpClientFactory.CreateClient();

            var temp = JsonConvert.SerializeObject(request.Content);

            var content = new StringContent(
                JsonConvert.SerializeObject(request.Content),
                System.Text.Encoding.UTF8,
                "application/json");

            var response = await client.PostAsync(
                $"https://qyapi.weixin.qq.com/cgi-bin/agent/set_workbench_data?access_token={token}",
                content);

            if (response.IsSuccessStatusCode)
            {
                var responseStream = await response.Content.ReadAsStreamAsync();

                using (responseStream)
                {
                    var res = await StreamToStringAsync(responseStream);
                    return res;
                }

            }

            response.EnsureSuccessStatusCode();
            return "推送错误";
        }
    }
}
